<!-- 电子签章待办/已办 -->
<template>
  <el-container class="electronicSealAgent">
    <el-header height="36px">
      <header-title :title="headerTitle" />
    </el-header>
    <el-main class="mainDetails">
      <!--      <iframe-->
      <!--        id="basicIframe"-->
      <!--        ref="basinRef"-->
      <!--        title="basicIframe"-->
      <!--        width="100%"-->
      <!--        style="overflow:hidden;border: none;"-->
      <!--        :height="basicHeight"-->
      <!--        :src="basinInfoSrc"-->
      <!--      />-->
      <jn-prj-detail :prj-id="prjId" :prj-type="prjType" />
    </el-main>
    <el-main class="mainDetails">
      <MyTable
        id="id"
        ref="myTableRef"
        :is-mar-class="true"
        :is-selection="false"
        :table-data="tableData"
        :columns="colOption"
        :table-operation="prjUrlParams.type === 'done' ? [] : btnOption"
        :col-option-enum="dicLists"
        @propClick="btnClick"
      >
        <template #state="{ scope }">
          <el-button class="pms-zr-tableColor" type="text" @click="goState(scope)">
            {{ dicLists['SIGN_STATE2'].find(sign => sign.dictId === scope.state).dictName || '' }}
          </el-button>
        </template>
      </MyTable>
      <pagination
        v-if="pageParam.total > 10"
        :total="pageParam.total"
        :page.sync="pageParam.pageNum"
        :limit.sync="pageParam.pageSize"
        @pagination="doSearch"
      />
    </el-main>
    <el-main class="mainDetails">
      <FooterBtn ref="footerBtnRef" :button-disable="prjUrlParams.type === 'done' ? btnOptionsB : btnOptionsnew" @handleNext="activeNext" @handleClose="activeClose" @handlereDeploy="activeRedeploy"/>
    </el-main>
    <!-- 打开签署状态弹框列表-审批流程 -->
    <el-dialog
      v-if="dialogState"
      v-dialogDrag
      title="审批流程"
      width="50%"
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :lock-scroll="true"
      class="pms-dialog"
      :visible.sync="dialogState"
    >
      <div class="dialogForm">
        <SignStatusList ref="signStatusRef" :sign-status-id="signStatusId" />
      </div>
    </el-dialog>
    <!-- 下一步 -->
    <next-page
      v-if="nextVisible"
      ref="nextPage"
      :visible.sync="nextVisible"
      :is-show-agent="false"
      @doNextEntity="nextPageRes"
    />
    <!-- 转派 -->
    <TransferPage
      v-if="transferPageVisible"
      :visible.sync="transferPageVisible"
      :process-inst-id="workDetail.processInstID"
      :org-id="_userInfo.parentWorkGroupId"
      :org-code="workDetail.orgCode"
      @redeployEntity="redeployEntity"
    />
  </el-container>
</template>

<script>
import HeaderTitle from '@/components/basic/HeaderTitle'
import MyTable from '@/components/basic/myTable'
import NextPage from '@/components/nextPerson/NextPage'
import SignStatusList from '@/components/eleSignature/signStatusList.vue'
import { getQueryObject, clonePage } from '@/utils'
import SysConst from '@/common/const'
import { colOption, btnOption, btnOptionsA, btnOptionsB } from '.'
import FooterBtn from '@/components/footer/details.vue'
import { getDropdownData } from '@/api/common' // 字典接口
import { queryDocTypeApi } from '@/api/attachManagement/electronicSign/electronicSignConfig'
import { getPrjStageApi } from '@/api/attachmentInfo'
import { getPrjDetail } from '@/api/checkoutValuation'
import { getTodoInfoApi, submitInstanceApi } from '@/api/attachManagement/electronicSign/electronicSignature'
import { getWFWorkItemApi } from '@/api/acceptanceManagement/acceptanceMange'
import JnPrjDetail from '@/components/jn/JnPrjDetail.vue'
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
import {
    confirmcDoReassignFlow,
} from '@/api/electSingnare/index'
export default {
    name: 'ElectronicSealAgent',
    components: {
        JnPrjDetail,
        HeaderTitle,
        MyTable,
        FooterBtn,
        NextPage,
        SignStatusList,
        TransferPage
    },
    data() {
        return {
            tableData: [], // 列表数据
            colOption, // 列表表头
            btnOption, // 列表按钮
            btnOptionsnew:[], // 待办底部按钮
            btnOptionsA,
            btnOptionsB, // 已办底部按钮
            dicLists: {}, // 下拉框字典选项集合
            basinInfoSrc: '', // 嵌套基本信息公共页面
            basicHeight: '', // 嵌套基本信息公共页面a高度
            prjUrlParams: {}, // 地址参数
            headerTitle: '', // 顶部标题文字
            nextVisible: false, // 下一步
            dialogState: false, // 审批流程列表弹框
            signStatusId: '', // 审批流程Id
            workFlowData: {
              activityInstID: '',
              processInstID: '', // 下一步
              activityDefID: '',
              processDefName: ''
            },
            total: 0, // 列表数据总数
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            prjId: '',
            prjType: '',
            transferPageVisible:false,
            workDetail:{},
            _userInfo:{}
        }
    },
    created() {
        this._userInfo = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')) || {}
        this.prjUrlParams = getQueryObject()
        document.title = this.prjUrlParams.type === 'done' ? '电子签章已办' : '电子签章待办'
        this.queryPrjDetail(this.prjUrlParams.workItemId)
        this.getDictData()
        this.getPrjStage()
        this.doSearch()
    },
    methods: {
        // 设置嵌套iframe地址
        iframeUrl(prjId) {
           // 基本信息
           // this.basinInfoSrc = `${process.env.VUE_APP_JUNNAN_IFRAME_URL}design/basicInfo?prjId=${prjId}`
           this.basinInfoSrc = `${process.env.VUE_APP_JUNNAN_IFRAME_URL}design/projectBasicInfo?prjId=${prjId}`
           window.addEventListener('message', this.handleMessage)
        },
        // 设置嵌套iframe高度
        handleMessage(event) {
          const base_url = ''
              if (event.origin === base_url) {
                return
              }
            console.log(event, 'event')
            if (event.data.type === 'basicHeight') {
                this.basicHeight = event.data.data + ''
            }
        },
        // 查看数据
        doSearch(item) {
            const params = {
                workItemId: this.prjUrlParams.workItemId,
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                isTodo: this.prjUrlParams.type === 'done' ? 0 : 1
            }
            console.log(params, '列表查询参数')
          getTodoInfoApi(params).then(res => {
            if (+res.code !== 200) {
              return Promise.reject(res)
            }   
                const _flags = res.data?.records?.some(items_=>items_.docType!=='TP01')
                this.btnOptionsnew = _flags?this.btnOptionsA.filter(_item=>!(['redeploy'].includes(_item))):this.btnOptionsA
                this.tableData = res.data?.records
                this.pageParam.total = res.data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            })
        },
        // 列表按钮点击事件
        btnClick(fun, row) {
            this[fun](row)
        },
        // 确认签署
        confirmSign(row) {
            if (!this.tableData.length) {
              return this.$message('暂无可签署文件')
            }
            window.open(this.tableData[0].signUrl, '_blank')
        },
        // 转派
      activeRedeploy() {
        this.transferPageVisible = true
      },
      async redeployEntity(item) {
        const params = {
          workItemId: this.workDetail.workItemID,
          userIds: item.empId,
          opinion: item.opinion,
          bizSeq: this.workDetail?.bizObject?.bizSeq,
          dealType: 'reassign'
        }
        const { code } = await confirmcDoReassignFlow(params)
        if (+code === 200) {
          this.$message.success('操作成功')
          clonePage()
        }
      },
        // 下一步
        activeNext() {
            if (!this.tableData.length) {
              return this.$message('暂无可待办文件')
            }
            this.nextVisible = true
        },
        // 下一步提交确认
        nextPageRes(info) {
            submitInstanceApi({ opinion: info.opinion, workItemId: this.prjUrlParams.workItemId }).then(res => {
              if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.nextVisible = false
                this.$message.success('提交成功')
                clonePage()
            })
        },
        // 点击签署状态
        goState(row) {
            console.log(row, '点击签署状态')
            this.dialogState = true
            this.signStatusId = row.fileViewId.toString()
        },
        // 关闭
        activeClose() {
            clonePage()
        },
        async queryPrjDetail(workItemId) {
            const workItem = await getWFWorkItemApi(workItemId)
            this.workDetail = workItem.data
            this.prjUrlParams.prjId = workItem.data.bizObject.prjId
            this.prjId = workItem.data.bizObject.prjId
            this.getBasicList(workItem.data.bizObject.prjId)
            this.queryDocType(workItem.data.bizObject.nodeCode)
            this.iframeUrl(workItem.data.bizObject.prjId)
        },
        // 获取基本信息
        async getBasicList(prjId) {
          getPrjDetail({ prjId }).then(res => {
            if (+res.code !== 200) {
                  return Promise.reject(res)
        }
            this.headerTitle = `${res.data.prjName}-${this.prjUrlParams.type === 'done' ? '电子签章已办' : '电子签章待办'}`
              this.prjType = res.data.prjType
          })
        },
        // 获取下拉框字典数据
        async getDictData() {
            const arr = ['SIGN_STATE2']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
        },
         // 获取文档类型
         async queryDocType(val) {
            const res = await queryDocTypeApi({ nodeId: val ?? '' })
            this.$set(this.dicLists, 'DOC_TYPE', res.data ?? [])
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            const stageData = res.data.map(item => ({
                    dictId: item.key,
                    dictName: item.value
                }))
            this.$set(this.dicLists, 'PRO_STAGE', stageData)
        }
    }
}
</script>

<style lang="scss" scoped>
.electronicSealAgent {
    width: 100%;
}
.mainDetails {
    padding: 15px 25px;
}
::v-deep .foldBox {
    padding: 20px 2px;
}
::v-deep .btnBox {
    padding-right: 10px;
}
</style>
